package com.nageoffer.shortlink.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageoffer.shortlink.admin.common.biz.user.UserContext;
import com.nageoffer.shortlink.admin.common.convention.exception.ClientException;
import com.nageoffer.shortlink.admin.common.convention.result.Result;
import com.nageoffer.shortlink.admin.common.database.BaseDo;
import com.nageoffer.shortlink.admin.common.toolkit.RandomGenerator;
import com.nageoffer.shortlink.admin.dao.entity.GroupDo;
import com.nageoffer.shortlink.admin.dao.mapper.GroupMapper;
import com.nageoffer.shortlink.admin.dto.req.ShortLinkGroupSortReqDto;
import com.nageoffer.shortlink.admin.dto.req.ShortLinkGroupUpdateReqDto;
import com.nageoffer.shortlink.admin.dto.resp.ShortLinkGroupRespDto;
import com.nageoffer.shortlink.admin.remote.ShortLinkActualRemoteService;
import com.nageoffer.shortlink.admin.remote.ShortLinkRemoteService;
import com.nageoffer.shortlink.admin.remote.dto.resp.ShortLinkCountQueryRespDto;
import com.nageoffer.shortlink.admin.service.GroupService;
import groovy.util.logging.Slf4j;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import cn.hutool.core.bean.BeanUtil;

import java.sql.Wrapper;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.nageoffer.shortlink.admin.common.constant.RedisCacheConstant.LOCK_GROUP_CREATE_KEY;

/**
 * 短链接接口实现层
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDo> implements GroupService {

    private final RedissonClient redissonClient;
    ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() {
    };
    private final ShortLinkActualRemoteService shortLinkActualRemoteService;

    @Value("${short-link.group.max-num}")
    private Integer groupMaxNum;

    @Override
    public void saveGroup(String groupName) {
        saveGroup(groupName, UserContext.getUsername());
    }

    @Override
    public void saveGroup(String groupName,String username) {
        RLock lock = redissonClient.getLock(String.format(LOCK_GROUP_CREATE_KEY, username));
        lock.lock();
        try {
            LambdaQueryWrapper<GroupDo> queryWrapper = Wrappers.lambdaQuery(GroupDo.class)
                    .eq(GroupDo::getUsername, username)
                    .eq(BaseDo::getDelFlag, 0);
            Long l = baseMapper.selectCount(queryWrapper);
            if (l>=groupMaxNum) {
                throw new ClientException("已超出最大分组数");
            }
            String gid;
            do {
                gid = RandomGenerator.generateRandomString();
            } while (hasGid(username,gid));
            GroupDo groupDo = GroupDo.builder().gid(gid).name(groupName).sortOrder(0).username(username).build();
            baseMapper.insert(groupDo);
        } catch (Exception e) {
            throw e;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public List<ShortLinkGroupRespDto> listGroup() {
        // TODO 获取用户名
        LambdaQueryWrapper<GroupDo> wrapper = Wrappers.lambdaQuery(GroupDo.class)
                .eq(BaseDo::getDelFlag,0)
                .eq(GroupDo::getUsername, UserContext.getUsername())
                .orderByAsc(GroupDo::getSortOrder, BaseDo::getUpdateTime);
        List<GroupDo> groupDoList = baseMapper.selectList(wrapper);
        Result<List<ShortLinkCountQueryRespDto>> listResult = shortLinkActualRemoteService.listGroupShortLinkCount(groupDoList.stream()
                .map(GroupDo::getGid).toList());
        List<ShortLinkGroupRespDto> shortLinkGroupRespDtoList = BeanUtil.copyToList(groupDoList, ShortLinkGroupRespDto.class);
        shortLinkGroupRespDtoList.forEach(each->{
            Optional<ShortLinkCountQueryRespDto> first = listResult.getData().stream()
                    .filter(item -> Objects.equals(each.getGid(), item.getGid()))
                    .findFirst();
            first.ifPresent(item->each.setShortLinkCount(first.get().getShortLinkCount()==null?0:first.get().getShortLinkCount()));
        });
        return shortLinkGroupRespDtoList;
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDto requestParam) {
        LambdaUpdateWrapper<GroupDo> wrapper = Wrappers.lambdaUpdate(GroupDo.class).eq(GroupDo::getGid, requestParam.getGid()).eq(GroupDo::getDelFlag, 0).eq(GroupDo::getUsername, UserContext.getUsername());
        GroupDo groupDo = new GroupDo();
        groupDo.setName(requestParam.getName());
        baseMapper.update(groupDo, wrapper);
    }

    @Override
    public boolean deleteGroup(String gid) {
        LambdaQueryWrapper<GroupDo> wrapper = Wrappers.lambdaQuery(GroupDo.class).eq(GroupDo::getGid, gid).eq(GroupDo::getDelFlag, 0);
        GroupDo groupDo = new GroupDo();
        groupDo.setDelFlag(1);
        int update = baseMapper.update(groupDo, wrapper);
        return update==1;
    }

    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDto> requestParam) {
        requestParam.forEach(each->{
            GroupDo groupDo = GroupDo.builder().sortOrder(each.getSortOrder()).build();
            LambdaUpdateWrapper<GroupDo> wrapper = Wrappers.lambdaUpdate(GroupDo.class).eq(GroupDo::getUsername,UserContext.getUsername()).eq(GroupDo::getGid, each.getGid()).eq(GroupDo::getDelFlag, 0);
            baseMapper.update(groupDo, wrapper);
        });
    }

    private boolean hasGid(String username,String gid){
        LambdaQueryWrapper<GroupDo> wrapper = Wrappers.lambdaQuery(GroupDo.class)
                // TODO 设置用户名
                .eq(GroupDo::getUsername, username)
                .eq(GroupDo::getGid, gid);
        GroupDo groupDo = baseMapper.selectOne(wrapper);
        return groupDo != null;
    }
}
